package com.jk.cxh.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.netflix.client.ClientException;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UploadImg {

    /**
     * @Author: SJD
     * @Description:上传阿里云 图片
     * @Date: 2021/5/19 22:50
     * @Param: [fileupload]
     * @Return: java.lang.String
     **/
    public static String getUrl(MultipartFile fileupload) throws OSSException, ClientException, IOException {
        //自己的keyid    key
        String ACCESS_KEY_ID = "LTAI4GHgGbd3DZExQjKJFsHF";
        String ACCESS_KEY_SECRET = "9WXqdd1iZRWzZBh5lMCLCVT4EgqFbA";
        // * 用户的存储空间（bucket）名称
        String BUCKET_NAME = "oss-yzq";
        // * 对应的映射域名
        final String ACCESS_URL = "";
        //* 用户的存储空间所在数据中心的访问域名
        final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 文件桶
        //       String BUCKET_NAME = "你的bucket";
        // 文件名格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        // 该桶中的文件key
        String dateString = sdf.format(new Date()) + ".jpg";//
        // 上传文件
        ossClient.putObject(BUCKET_NAME, dateString, new ByteArrayInputStream(fileupload.getBytes()));
        // 设置URL过期时间为100年，默认这里是int型，转换为long型即可
        Date expiration = new Date(new Date().getTime() + 3600L * 1000 * 24 * 365 * 100);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(BUCKET_NAME, dateString, expiration);
        return url.toString();
    }
}
